﻿using eProcurement.BLL;
using eProcurement.controls;
using eProcurement.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace eProcurement.members
{
    public partial class MyProjects : System.Web.UI.Page
    {
        protected void Page_Load( object sender, EventArgs e )
        {
            if ( !IsPostBack )
            {
                List<Project> projects = new List<Project>();
                Manager manager = new Manager();

                Purchaser purchaser = (Purchaser)manager.GetAppUser( Context.User.Identity.Name );

                if ( purchaser != null )
                {
                    if ( Request[ "state" ] == null )
                    {
                        projects = purchaser.Projects.OrderBy( x => x.CloseDate ).ToList();
                    }
                    else if ( Request[ "state" ] == ProjectState.OPEN.ToString() )
                    {
                        projects = ( from i in purchaser.Projects
                                     where i.State == "OPEN"
                                     select i ).ToList();
                    }
                    else if ( Request[ "state" ] == ProjectState.CANCELLED.ToString() )
                    {
                        projects = ( from i in purchaser.Projects
                                     where i.State == ProjectState.CANCELLED.ToString()
                                     select i ).ToList();
                    }
                    else if ( Request[ "state" ] == ProjectState.CLOSED.ToString() )
                    {
                        projects = ( from i in purchaser.Projects
                                     where i.State == ProjectState.CLOSED.ToString()
                                     select i ).ToList();
                    }
                }

                HydrateTable( projects );
            }
        }

        private void HydrateTable( List<Project> projects )
        {
            foreach ( Project project in projects )
            {
                MyProjectsItemControl control = (MyProjectsItemControl)LoadControl( "../controls/MyProjectsItemControl.ascx" );
                control.Setup( project );
                container.Controls.Add( control );
            }
        }
    }
}